<?php
error_reporting(E_STRICT | E_ALL);

// Provide AdWords login information.
$email = 'info@ua-solutions.com';
$password = 'uasolutions';

$params = array(
    'Email' => $email,
    'Passwd' => $password,
    'accountType' => 'GOOGLE',
    'service' => 'adwords',
    'source' => 'AdWords API PHP Code Example');

$url = 'https://www.google.com/accounts/ClientLogin';

// Make request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);

// Parse response.
$lines = explode("\n", $response);
foreach ($lines as $line) {
  $parts = explode('=', $line, 2);
  if ($parts[0] == 'Auth') {
    $authToken = $parts[1];
  }
  if ($parts[0] == 'Error') {
    $error = $parts[1];
  }
}

// Display results.
if (isset($authToken)) {
  print 'Auth token: ' . $authToken . "\n";
} else if (isset($error)) {
  print 'Error: ' . $error . "\n";
}

// Provide header information.
//$authToken = 'INSERT_AUTH_TOKEN_HERE';
$clientCustomerId = '489-314-3321';
$userAgent = 'uasolutions: AdWords API PHP Code Example';
$developerToken = 'pEGGOZ84xYlJktXyXJnSKg'; 

// Set SOAP and XML settings. To send requests to production environment,
// replace "adwords-sandbox.google.com" with "adwords.google.com" in the wsdl
// URL. The namespace will always be "adwords.google.com", even in the
// sandbox.
//$wsdl = 'https://adwords-sandbox.google.com/api/adwords/cm/v201109/CampaignService?wsdl';
$wsdl = 'https://adwords.google.com/api/adwords/cm/v201302/CampaignService?wsdl';
$namespace = 'https://adwords.google.com/api/adwords/cm/v201302';
$options = array(
    'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
    'encoding' => 'utf-8');

// Get CampaignService.
$campaignService = new SoapClient($wsdl, $options);

// Set headers.
$headers = new SoapHeader($namespace, 'RequestHeader', array(
    'authToken' => $authToken,
    'clientCustomerId' => $clientCustomerId,
    'userAgent' => $userAgent,
    'developerToken' => $developerToken));
$campaignService->__setSoapHeaders($headers);

// Create campaign.
$campaign = array(
    'name' => 'Interplanetary Cruise #' . time(),
    'status' => 'PAUSED',
    'biddingStrategy' => new SoapVar(NULL, NULL, 'ManualCPC', $namespace),
    'budget' => array(
        'period' => 'DAILY',
        'amount' => array('microAmount' => 50000000),
        'deliveryMethod' => 'STANDARD'));

// Create operations.
$operation = array('operator' => 'ADD', 'operand' => $campaign);
$operations = array($operation);

try {
  // Add campaign.
  $result = $campaignService->mutate($operations);
} catch (SoapFault $e) {
  //print_r($e);
 //exit(1);
}

// Display results.
/*foreach ($result->rval->value as $campaign) {
  print 'Campaign with name "' . $campaign->name . '" and id "'
      . $campaign->id . "\" was added.\n";
}*/

// Create report definition XML.
$reportDefinition = <<<EOT
<reportDefinition xmlns="https://adwords.google.com/api/adwords/cm/v201302">
  <selector>
    <fields>CampaignId</fields>
    <fields>Id</fields>
    <fields>Impressions</fields>
    <fields>Clicks</fields>
    <fields>Cost</fields>
    <predicates>
      <field>Status</field>
      <operator>IN</operator>
      <values>ENABLED</values>
      <values>PAUSED</values>
    </predicates>
  </selector>
  <reportName>Custom Adgroup Performance Report</reportName>
  <reportType>ADGROUP_PERFORMANCE_REPORT</reportType>
  <dateRangeType>LAST_7_DAYS</dateRangeType>
  <downloadFormat>CSV</downloadFormat>
</reportDefinition>
EOT;

// Create parameters.
$params = array('__rdxml' => $reportDefinition);

// Create headers.
$headers = array();
$headers[]= 'Authorization: GoogleLogin auth=' . $authToken;
$headers[]= 'clientCustomerId: ' . $clientCustomerId;
$headers[]= 'developerToken: ' . $developerToken;

$downloadPath = 'report.csv';
$url = 'https://adwords.google.com/api/adwords/reportdownload/v201302';

$file = fopen($downloadPath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($file);

if ($code == 200) {
  printf("Report downloaded to: %s\n", $downloadPath);
} else {
  $file = fopen($downloadPath, 'r');
  $error = fread($file, 1024);
  fclose($file);
  printf("Error: %s\n", $error);
}

// Provide header information.
$apiVersion = 'v201302';

// Create report definition XML.
$reportDefinition = 'SELECT CampaignId, Id, Impressions, Clicks, Cost ' .
  '  FROM ADGROUP_PERFORMANCE_REPORT ' .
  'WHERE Status IN ["ENABLED","PAUSED"]' .
  '  DURING LAST_7_DAYS';

$format = 'CSV';

// Create parameters.
$params = array(
  '__rdquery' => $reportDefinition,
  '__fmt' => $format,
);

// Create headers.
$headers = array();
$headers[]= 'Authorization: GoogleLogin auth=' . $authToken;
$headers[]= 'clientCustomerId: ' . $clientCustomerId;
$headers[]= 'developerToken: ' . $developerToken;

$downloadPath = 'report.csv';
$url = "https://adwords.google.com/api/adwords/reportdownload/$apiVersion";

$file = fopen($downloadPath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($file);

if ($code == 200) {
  printf("Report downloaded to: %s\n", $downloadPath);
} else {
  $file = fopen($downloadPath, 'r');
  $error = fread($file, 1024);
  fclose($file);
  printf("Error: %s\n", $error);
}